<?

class ShowList extends db {
	
	var $toSearch = 'upcoming';
	var $includeAV = 0;
	var $includePictures = 0;
	var $isAllAges = null;
	var $keywords = null;
	var $isActive = true;
	
	var $limit = 10;
	var $current = 0;
	var $orderBy = "desc";
	var $orderColumn = "date";
	
	function includeAll() {
		$this->isActive = null;
	}
	
	function _buildQ($fullQuery = false) {
		$clauses = 0;
		$q = 'left join Venues on Shows.venue_id = Venues.ID ';
		if ($this->includeAV) { 
			$q .= "inner join DarkRoom_Media_to_Areas da1 on (da1.area_id = Shows.av_area_id) ";
		}
		
		if ($this->includePictures) { 
			$q .= "inner join DarkRoom_Media_to_Areas da2 on (da2.area_id = Shows.photo_area_id) ";
		}
		
		if (isset($this->isActive)) {
			$q .= "where Shows.is_active = {$this->isActive} ";
			$clauses++;
		}
		
		if ($this->isAllAges != null) {
			$q .= ($clauses > 0) ? "and " : "where ";
			$q .= "Shows.is_all_ages = {$this->isAllAges} ";
			$clauses++;
		}
		
		if ($this->keywords != null) {
			$q .= ($clauses > 0) ? "and " : "where ";
			$q .= "(Shows.name like '%{$this->keywords}%' or Venues.name like '%{$this->keywords}%' or Shows.other_bands like '%{$this->keywords}%' or Shows.notes like '%{$this->keywords}%') ";
			$clauses++;

		}	
				
		if ($this->toSearch == 'upcoming') { 
			$q .= ($clauses > 0) ? "and Shows.date >= NOW() " : "where date >= NOW() ";
			$clauses++;

		}
		
		if ($fullQuery) {
			$q .= "order by {$this->orderColumn} {$this->orderBy} limit {$this->current}, {$this->limit} ";
		}
		return $q;
	}
	
	function getTotal() {
		$q = "select count(*) as total from Shows " . $this->_buildQ();
		$r = mysql_query($q);
		$row = mysql_fetch_assoc($r);
		return $row['total'];
	}
	
	function get() {
		$args_list = func_get_args();
		$limit = (int) $args_list[0];
		$current = (int) $args_list[1];
		
		if ($limit) {
			$this->limit = $limit;
		}
		if ($current) {
			$this->current = $current;
		}
		
		$q = "select Shows.ID from Shows " . $this->_buildQ(true);
		$r = mysql_query($q);
	
		if ($r) {
			$shows = array();
			while ($row = mysql_fetch_assoc($r)) {
				$shows[] = Show::get($row['ID']);
			}
			return $shows;
		} else {
			return Error::MySQL();
		}
	}	
}

class Show extends db {

	var $ID, $date, $venue, $time, $other_bands, $cost, $is_all_ages, $notes, $user_id, $is_active, $av_area_id, $photo_area_id;
	
	function get($showID) {
		if (is_numeric($showID) && $showID > 0) {
			$q = "select * from Shows where ID = " . $showID;
			$db = new db;
			$r = mysql_query($q);
			if (!$r) {
				return Error::MySQL();
			}
			
			$row = mysql_fetch_assoc($r);
			if ($row['ID']) {
				$sh = new Show;
				$sh->ID = $row['ID'];
				$sh->date = $db->sanitize_from_db($row['date']);
				$sh->name = $db->sanitize_from_db($row['name']);
				$sh->time = $db->sanitize_from_db($row['time']);
				$sh->other_bands = $db->sanitize_from_db($row['other_bands']);
				$sh->cost = $db->sanitize_from_db($row['cost']);
				$sh->is_all_ages = $row['is_all_ages'];
				$sh->notes = $db->sanitize_from_db($row['notes']);
				$sh->user_id = $row['user_id'];		
				$sh->is_active = $row['is_active'];
				$sh->venue_id = $row['venue_id'];
				$sh->av_area_id = $row['av_area_id'];
				$sh->photo_area_id = $row['photo_area_id'];
				
				return $sh;
			}
		}
		
		return Error::create("Invalid show ID.");
	}
	
	function getID() {return $this->ID;}
	function getDate($dateMask = null) {
		$dateMask = (!$dateMask) ? DATE_FORMAT : $dateMask;
		return date($dateMask, strtotime($this->date));
	}
	function getTime($dateMask = null) {
		$dateMask = (!$dateMask) ? TIME_FORMAT : $dateMask;
		if ($this->time == null) {
			return SHOW_TBD;
		} else {
			return date($dateMask, strtotime($this->time));
		}
	}
	function getTimeValue() {
		$dateMask = TIME_FORMAT;
		if ($this->time == null) {
			return "";
		} else {
			return date($dateMask, strtotime($this->time));
		}
	}
	function getName() {return $this->name;}
	function getOtherBands() {return $this->other_bands;}
	function getCost() {
		if ($this->cost == null) {
			return SHOW_TBD;
		} else if ($this->cost == '0.00') {
			return SHOW_FREE;
		} else {
			return '$'.$this->cost;
		}
	}
	function getAVAreaID() {return $this->av_area_id;}
	function getAVAreaObject() {
		if ($this->av_area_id > 0) {
			$ma = MediaArea::get($this->av_area_id);
			return $ma;
		} else {
			$e = new Error();
			$e->add("An administrator has not yet registered this show for audio or videos.");
			return $e;
		}
	}
	function getPhotoAreaID() {return $this->photo_area_id;}
	function getPhotoAreaObject() {
		if ($this->photo_area_id > 0) {
			$ma = MediaArea::get($this->photo_area_id);
			return $ma;
		} else {
			$e = new Error();
			$e->add("An administrator has not yet registered this show for photos.");
			return $e;
		}
	}
	function getCostValue() {return $this->cost;}
	function isAllAges() {return $this->is_all_ages;}
	function getNotes() {return $this->notes;}
	
	function isActive() {return $this->is_active;}
	function getUserID() {return $this->user_id;}
	function getUserObject() {
		$uo = User::get($this->user_id);
		return $uo;
	}
	function getVenueObject() {
		if ($this->venue_id > 0) {
			$ve = Venue::get($this->venue_id);
			return $ve;
		}
	}
	function getVenueID() {
		return $this->venue_id;
	}
	
	function canEdit() {
		$uo = User::getCurrent();		
		if (is_object($uo)) {
			return ($uo->getID() == $this->getUserID() || $uo->isAdmin());
		}
	}
	
	function canAdd() {
		$uo = User::getCurrent();		
		if (is_object($uo)) {
			return ($uo->isBandMember() || $uo->isAdmin());
		}
	}	
	
	function getTourObject() {
		$q = "select Tours.ID from Shows, Tours where Shows.date >= Tours.start_date and Shows.date <= Tours.end_date and Shows.ID = " . $this->ID;
		$r = mysql_query($q);
		if (!$r) {
			return Error::MySQL();
		}
		$row = mysql_fetch_assoc($r);
		$to = Tour::get($row['ID']);
		return $to;
	}
	
	function getPreviousShow() {
		$q = "select ID from Shows where (date < '{$this->date}' or (date = '{$this->date}' and time < '{$this->time}')) and is_active = 1 order by date desc limit 1";
		$r = mysql_query($q);
		if (!$r) {
			return Error::MySQL();
		}
		$row = mysql_fetch_assoc($r);
		$bs = Show::get($row['ID']);
		return $bs;
	}
	
	function getNextShow() {
		$q = "select ID from Shows where (date > '{$this->date}' or (date = '{$this->date}' and time > '{$this->time}')) and is_active = 1 order by date asc limit 1";
		$r = mysql_query($q);
		if (!$r) {
			return Error::MySQL();
		}
		$row = mysql_fetch_assoc($r);
		$bs = Show::get($row['ID']);
		return $bs;
	}
	
	function activate() {
		if ($this->canEdit()) {
			$r = @mysql_query("update Shows set is_active = 1 where ID = " . $this->ID);
			if (!$r) {
				return Error::MySQL();
			}
		} else {
			return Error::create('You may not activate a show you did not post.');
		}
	}
	
	function deactivate() {
		if ($this->canEdit()) {
			$r = @mysql_query("update Shows set is_active = 0 where ID = " . $this->ID);
			if (!$r) {
				return Error::MySQL();
			}
		} else {
			return Error::create('You may not deactivate a show you did not post.');
		}
	}
	
	function remove() {
		if (User::isAdmin()) {
			$r = @mysql_query("delete from Shows where ID = " . $this->ID);
			if (!$r) {
				return Error::MySQL();
			}
		} else {
			return Error::create('Only an administrator may delete shows.');
		}
	}
	
	function update($postArray) { 
		$db = new db;
		include_class('band_members');
		include_class('venues');
		
		$e = new Error();
		
		if (!$this->canEdit()) {
			return Error::create("You may not update a show you did not post.");
		}
		
		$name = $db->sanitize_to_db($postArray['name']);
		$dt = $db->sanitize_to_db($postArray['date']);
		$date = date("Y-m-d", strtotime($dt));
				
		if ($postArray['time']) {
			$time = $db->sanitize_to_db($postArray['time']);
			$time = "'" . date("H:i:s", strtotime($time)) . "'";
		} else {
			$time = "null";
		}
			
		if ($postArray['cost'] != "") {
			$cost = $db->sanitize_to_db($postArray['cost']);
			$cost = "'{$cost}'";
		} else {
			$cost = "null";
		}
		
		$is_all_ages = ($postArray['is_all_ages'] == '1') ? 1 : 0;
		$other_bands = $db->sanitize_to_db($postArray['other_bands']);
		$notes = $db->sanitize_to_db($postArray['notes']);
		
		if (User::isAdmin()) {
			$uo = User::get($postArray['user_id']);
			if (db::isError($uo)) {
				$e->add($uo);
			} else if (!$uo->isAdmin() && $uo->isBandMember() ) {
				$e->add("Invalid user. User must be a band member or an administrator.");
			}
		} else {
			$uo = User::getCurrent();
		}
		
		if ($postArray['venue_id'] != '0') {
			$ve = Venue::get($postArray['venue_id']);
		}
		
		if (db::isError($ve)) {
			$e->add($ve);
		}
		
		if ($e->hasErrors()) {
			return $e;
		}
		
		$user_id = $uo->getID();
		$venue_id = $db->sanitize_to_db($postArray['venue_id']);

		if (!$name) {
			$name = (is_object($ve) && !db::isError($ve)) ? $db->sanitize_to_db($ve->getName()) : "(untitled show)";
		}
		
		$r = @mysql_query("update Shows set name='$name', venue_id = '{$venue_id}', date='$date', time = $time, user_id = '$user_id', cost={$cost}, is_all_ages = '$is_all_ages', other_bands='$other_bands', notes='$notes' where ID = " . $this->ID);
		if ($r) {
			return Show::get($this->ID);
		} else {
			return Error::MySQL();
		}
	}
	
	function add($postArray) {
		$db = new db;
		include_class('venues');
		
		$e = new Error();
		
		$name = $db->sanitize_to_db($postArray['name']);
		$dt = $db->sanitize_to_db($postArray['date']);
		$date = date("Y-m-d", strtotime($dt));
				
		if ($postArray['time']) {
			$time = $db->sanitize_to_db($postArray['time']);
			$time = "'" . date("H:i:s", strtotime($time)) . "'";
		} else {
			$time = "null";
		}
			
		if ($postArray['cost'] != "") {
			$cost = $db->sanitize_to_db($postArray['cost']);
			$cost = "'{$cost}'";
		} else {
			$cost = "null";
		}
		
		$is_all_ages = ($postArray['is_all_ages'] == '1') ? 1 : 0;
		$other_bands = $db->sanitize_to_db($postArray['other_bands']);
		$notes = $db->sanitize_to_db($postArray['notes']);
		
		if (User::isAdmin()) {
			$uo = User::get($postArray['user_id']);
			if (db::isError($uo)) {
				$e->add($uo);
			} else if (!$uo->isAdmin() && $uo->isBandMember()) {
				$e->add("Invalid user. User must be a band member or an administrator.");
			}
		} else {
			$uo = User::getCurrent();
		}
		
		if ($postArray['venue_id'] != '0') {
			$ve = Venue::get($postArray['venue_id']);
		}
		
		if (db::isError($ve)) {
			$e->add($ve);
		}
		
		if ($e->hasErrors()) {
			return $e;
		}
		
		$user_id = $uo->getID();
		$venue_id = $db->sanitize_to_db($postArray['venue_id']);

		if (!$name) {
			$name = (is_object($ve) && !db::isError($ve)) ? $db->sanitize_to_db($ve->getName()) : "(untitled show)";
		}
		
		$r = mysql_query("insert into Shows (name, venue_id, date, time, user_id, cost, is_all_ages, other_bands, notes, is_active) values ('$name', '$venue_id', '$date', $time, $user_id, {$cost}, $is_all_ages, '$other_bands', '$notes'," . DEFAULT_ACTIVE . ")");	
		if ($r) {
			return Show::get(mysql_insert_id());
		} else {
			return Error::MySQL();
		}
	}
	
	function registerMedia($mediaType) {
		$type = ($mediaType == 'av') ? 'av' : 'photos';
		if (User::isAdmin()) { 
			if (($type == 'av' && $this->av_area_id < 1) || ($type == 'photos' && $this->photo_area_id < 1)) {
				$areaTitle = ($type == 'av') ? "Show Audio/Video: " : "Show Photos: ";
				$areaIDField = ($type == 'av') ? "av_area_id" : "photo_area_id";
				if ($type == 'av') {
					$allowed_extensions = MEDIA_EXTENSIONS_ALLOWED_AV;
					$display = "list";
				} else {
					$allowed_extensions = MEDIA_EXTENSIONS_ALLOWED_PHOTO;
					$display = "grid";
				}
				
				$ma = MediaArea::add(0, $areaTitle . $this->name, null, $allowed_extensions, $display);
				if (db::isError($ma)) {
					return $ma;
				}
				
				$ma->activate();
				$q = "update Shows set {$areaIDField} = " . $ma->getID() . " where ID = {$this->ID}";
				$r = mysql_query($q);
				if (!$r) {
					return Error::MySQL();
				} else {
					return $r;
				}
			} else {
				return Error::create("A show with an ID of {$this->ID} is already registered.");
			}
		} else {
			return Error::create('Only an admin user may authorize a show for media.');
		}
	}
	
	function validateMediaOperation($opType = "ADD", $mediaObject = null) {
		// called automatically by the m2 functions that add media, when passed the object
		// opType allows us to distinguish between adding, editing, updating, etc... but most times
		// the same check will work for all operation types
		if ($opType == "RESCAN") {
			// non-admins can't delete, only deactivate
			if (!User::isAdmin()) {
				return Error::create('Only an admin user may rescan media.');
			} else {
				return true;
			}
		} else {
			if (!User::isAdmin()) {
				return Error::create('Only an admin user may add, delete, activate or deactivate show media.');
			} else {
				return true;
			}
		}
	}
}

// PHP Calendar Class Version 1.4 (5th March 2001)
//  
// Copyright David Wilkinson 2000 - 2001. All Rights reserved.
// 
// This software may be used, modified and distributed freely
// providing this copyright notice remains intact at the head 
// of the file.
//
// This software is freeware. The author accepts no liability for
// any loss or damages whatsoever incurred directly or indirectly 
// from the use of this script. The author of this software makes 
// no claims as to its fitness for any purpose whatsoever. If you 
// wish to use this software you should first satisfy yourself that 
// it meets your requirements.
//
// URL:   http://www.cascade.org.uk/software/php/calendar/
// Email: davidw@cascade.org.uk


// Audition TO-DO: completely rewrite. This is an interim hack. Most of this logic 
// needs to be moved into the presentation layer.

class ShowCalendar {
		
		var $startDay = 0;
	    var $startMonth = 1;
		var $dayNames = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    	var $monthNames = array("January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December");
	    var $daysInMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    	var $activeDay;
		var $activeMonth;
		var $activeYear;
		var $showsArray = array();
		
		function getDayNames() {
    	    return $this->dayNames;
    	}
   
		function getMonthNames() {
			return $this->monthNames;
		}
	  	
		function getStartDay() {
			return $this->startDay;
		}
	
		function setStartDay($day) {
			$this->startDay = $day;
		}
		
		function getStartMonth() {
			return $this->startMonth;
		}
		
		function setStartMonth($month) {
			$this->startMonth = $month;
		}
		
		
		function getActiveDay() {
			return $this->activeDay;
		}
		
		function populateShowsArray($m, $y) {
			$db = new db;
			$mPadded = sprintf("%02d", $m);
			$q = "select DATE_FORMAT(date, '%d') as day, ID from Shows where is_active = 1 and DATE_FORMAT(date, '%m') = '{$mPadded}' and DATE_FORMAT(date, '%Y') = '{$y}' order by date asc";
			$r = mysql_query($q);
			if ($db->isError($r)) {
				return Error::MySQL();
			}
			while ($row = mysql_fetch_assoc($r)) {
				$this->showsArray[(int) $row['day']][] = Show::get($row['ID']);
			}
		}
		
		function getCalendar($m, $y) {
			$db = new db;
			
			$this->activeDay = $db->get_local_datetime('d');
			$this->activeMonth = $db->get_local_datetime('m');
			$this->activeYear = $db->get_local_datetime('Y');
						
			$m = (is_numeric($m)) ? $m : $this->activeMonth;
			$y = (is_numeric($y)) ? $y : $this->activeYear;
			
			$this->populateShowsArray($m, $y);
			
			$a = $this->adjustDate($m, $y);
			$month = $a[0];
			$year = $a[1];			
			
			$daysInMonth = $this->getDaysInMonth($month, $year);
			$date = getdate(mktime(12, 0, 0, $month, 1, $year));
			
			$first = $date["wday"];
			$monthName = $this->monthNames[$month - 1];
			
			$prev = $this->adjustDate($month - 1, $year);
			$next = $this->adjustDate($month + 1, $year);
			
			if ($previousMonthLink && $nextMonthLink) {	
				$prevMonth = $previousMonthLink;
				$nextMonth = $nextMonthLink;
			}
			
			$calMonth = ($m == "1") ? "12" : $m - 1;
			$calYear = ($m == "1") ? $y - 1 : $y;
			if (USE_MOD_REWRITE) { 
				$prevURL = SITE_WEB_DIRECTORY . "/shows/{$calYear}/{$calMonth}/";
			} else {
				$prevURL = SITE_WEB_DIRECTORY . "/shows.php?year={$calYear}&month={$calMonth}";
			}
			
			$calMonth = ($m == "12") ? "1" : $m + 1;
			$calYear = ($m == "12") ? $y + 1 : $y;
			if (USE_MOD_REWRITE) { 
				$nextURL = SITE_WEB_DIRECTORY . "/shows/{$calYear}/{$calMonth}/";
			} else {
				$nextURL = SITE_WEB_DIRECTORY . "/shows.php?year={$calYear}&month={$calMonth}";
			}
			
			$header = $monthName . " " . $year;
			
			$s .= "<table class=\"calendar-header\">";
			$s .= "<tr><td class=\"back\"><a href=\"{$prevURL}\">&lt;&lt;</a></td>";
			$s .= "<td>{$header}</td>";
			$s .= "<td class=\"forward\"><a href=\"{$nextURL}\">&gt;&gt;</a></td></tr></table>";
			$s .= "<table class=\"calendar\" width=\"100%\" cellspacing=\"2\" border=\"0\" cellpadding=\"0\">";
			$s .= "<tr>";
			$s .= "<td align=\"center\" valign=\"top\" class=\"day\">" . $this->dayNames[($this->startDay)%7] . "</td>";
			$s .= "<td align=\"center\" valign=\"top\" class=\"day\">" . $this->dayNames[($this->startDay+1)%7] . "</td>";
			$s .= "<td align=\"center\" valign=\"top\" class=\"day\">" . $this->dayNames[($this->startDay+2)%7] . "</td>";
			$s .= "<td align=\"center\" valign=\"top\" class=\"day\">" . $this->dayNames[($this->startDay+3)%7] . "</td>";
			$s .= "<td align=\"center\" valign=\"top\" class=\"day\">" . $this->dayNames[($this->startDay+4)%7] . "</td>";
			$s .= "<td align=\"center\" valign=\"top\" class=\"day\">" . $this->dayNames[($this->startDay+5)%7] . "</td>";
			$s .= "<td align=\"center\" valign=\"top\" class=\"day\">" . $this->dayNames[($this->startDay+6)%7] . "</td>";
			$s .= "</tr>\n";
			
			// We need to work out what date to start at so that the first appears in the correct column
			$d = $this->startDay + 1 - $first;
			while ($d > 1)
			{
				$d -= 7;
			}
	
			$week = 1;
			while ($d <= $daysInMonth)
			{
				
				$s .= "<tr>";       
				
				for ($i = 0; $i < 7; $i++)
				{
					$hasShows = (is_array($this->showsArray[$d])) ? true : false;
					$activeClass = ($hasShows) ? "shows" : "";
					$s .= ($this->activeDay == $d && $m == $this->activeMonth && $y = $this->activeYear) ? "<td class=\"today{$activeClass}\" valign=\"top\">" : "<td class=\"{$activeClass}\" valign=\"top\">";
					
					if ($d > 0 && $d <= $daysInMonth) {						
						$s .= '<div class="number">' . $d . '</div>';										
	
						if ($hasShows) { 
							foreach($this->showsArray[$d] as $so) {
								$s .= "<div class=\"show\">";
								if (USE_MOD_REWRITE) {
									$s .= "<a href=\"" . SITE_WEB_DIRECTORY . "/show/" . $so->getID() . "\">" . $so->getName() . "</a>";
								} else {
									$s .= "<a href=\"" . SITE_WEB_DIRECTORY . "/shows.php?id=" . $so->getID() . "\">" . $so->getName() . "</a>";
								}
							}
						}
														
					} else {
						
						$s .= "&nbsp;";
					}
					
					$s .= "</td>";       
					$d++;
				}
				$s .= "</tr>";    
				$week++;
			}
			
			$s .= "</table>";
			
			return $s;  	
		}
		
		function getDaysInMonth($month, $year) {
			if ($month < 1 || $month > 12) {
				return 0;
			}
	   
			$d = $this->daysInMonth[$month - 1];
	   
			if ($month == 2) {
				// Check for leap year
				// Forget the 4000 rule, I doubt I'll be around then...
			
				if ($year%4 == 0) {
					if ($year%100 == 0) {
						if ($year%400 == 0) {
							$d = 29;
						}
					} else {
						$d = 29;
					}
				}
			}
		
			return $d;
		}
		
		function adjustDate($month, $year) {
			$a = array();  
			$a[0] = $month;
			$a[1] = $year;
			
			while ($a[0] > 12) {
				$a[0] -= 12;
				$a[1]++;
			}
			
			while ($a[0] <= 0) {
				$a[0] += 12;
				$a[1]--;
			}
			
			return $a;
		}	
    
	
	}
?>